﻿

using ExcelDataReader;
using Ixxat.Vci3;
using Ixxat.Vci3.Bal;
using Ixxat.Vci3.Bal.Can;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace IXXAT
{
    public partial class MainForm2 : Form
    {
        //全局定义
        #region
        public static string Address = "Address";
        public static string DataDype = "Data type";
        public static string Gain = "Gain";
        public static string Offset = "Offset";
        public static string BaseValue = "BaseValue";
        public static string Decimal = "Decimal";
        public static string Max = "Max";
        public static string Min = "Min";
        public static string StratBit = "Start bit";

        public static object[] aAddress = new object[len];
        public static int[] aDataDype = new int[len];
        public static int[] aGain = new int[len];
        public static int[] aOffset = new int[len];
        public static double[] aBaseValue = new double[len];
        public static int[] aDecimal = new int[len];
        public static int[] aMax = new int[len];
        public static int[] aMin = new int[len];
        public static int[] aStratBit = new int[len];
        private static ThreadStart openfile;

        public static byte[] si = new byte[aAddress.Length];
        public static byte[] low = new byte[aAddress.Length];
        public static byte[] Subindex = new byte[aAddress.Length];
        private static byte[] Read = new byte[8];
        private static byte[] modify = new byte[8];

        public static MainForm form = new MainForm();
        public static int row;
        public static byte[] command = new byte[2];
        public static int intright;
        public static int intleft;
        public static UInt16[] uint16buf = new UInt16[aAddress.Length];
        public static Int16[] int16buf = new Int16[aAddress.Length];
        public static string[] Slow = new string[aAddress.Length];
        public static string[] Ssi = new string[aAddress.Length];
        int[] a = new int[100];

        public MainForm2()
        {

            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
           
        }
        #endregion

        //修改按钮
        #region
        //修改单元格并解析成一条ID发送给控制器
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                timer1.Enabled = true;
                //this.dataGridView["列名称或列下标索引", "行下标索引"].Value = "Test";
                string value = dgvData.CurrentCell.Value.ToString();
                row = dgvData.CurrentRow.Index;

                double intvalue = Convert.ToDouble(value);
                Analysis(intvalue);


                if (MainForm2.aDataDype[row] == 1)
                {
                    intright = int16buf[row] & 0xff;  // 低八位
                    intleft = MainForm.int16resdata[row] >> 8;
                    command[1] = (byte)intright;
                    command[0] = (byte)intleft;

                }
                else
                    intright = uint16buf[row] & 0x00ff;  // 低八位
                intleft = uint16buf[row] >> 8;
                command[1] = (byte)intright;
                command[0] = (byte)intleft;
                //改
                modify[0] = 0x22;
                modify[1] = low[row];
                modify[2] = si[row];
                modify[3] = Subindex[row];
                modify[4] = command[1];
                modify[5] = command[0];
                form.DatatoSend(0x62C, modify);
                Thread.Sleep(10);
                //读
                Read[0] = 0x42;
                Read[1] = low[row];
                Read[2] = si[row];
                Read[3] = Subindex[row];
                form.DatatoSend(0x62C, Read);
                if (aDataDype[row] == 0)
                {
                    if ((int)dgvData.Rows[row].Cells["实际值"].Value != MainForm.uint16resdata[row])
                    {
                        Thread.Sleep(1000);
                    }
                    if ((int)dgvData.Rows[row].Cells["实际值"].Value == MainForm.uint16resdata[row])

                    {
                        MessageBox.Show("修改正确!");
                    }
                    else
                    {
                        MessageBox.Show("修改错误!");
                    }
                }
                if (aDataDype[row] == 1)
                {
                    if ((int)dgvData.Rows[row].Cells["实际值"].Value != MainForm.int16resdata[row])
                    {
                        Thread.Sleep(1000);
                    }
                    if ((int)dgvData.Rows[row].Cells["实际值"].Value == MainForm.int16resdata[row])
                    {
                        MessageBox.Show("修改正确!");
                    }
                    else
                    {
                        MessageBox.Show("修改错误!");
                    }
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }
            
        #endregion

        //保留小数
        #region    
        public static double RecDecimal(double Data, int Precision)
        {
            switch (Precision)
            {
                case 0:
                    Data = Data * Math.Pow(10, 0);
                    return Data;
                case 1:
                    Data = Data * Math.Pow(10, 1);
                    return Data;
                case 2:
                    Data = Data * Math.Pow(10, 2);
                    return Data;
                case 3:
                    Data = Data * Math.Pow(10, 3);
                    return Data;
                case 4:
                    Data = Data * Math.Pow(10, 4);
                    return Data;
                case 5:
                    Data = Data * Math.Pow(10, 5);
                    return Data;
                default:

                    return Data;
            }
        }



        public void Analysis(double Data)
        {
            Data = RecDecimal(Data, aDecimal[row]);
            Data = (Data * aBaseValue[row] - aOffset[row]) / aGain[row];
            if (aDataDype[row] == 0)
            {
                uint16buf[row] = Convert.ToUInt16(Data);
                dgvData.Rows[row].Cells["实际值"].Value = uint16buf[row];
            }
            if (aDataDype[row] == 1)
            {
                int16buf[row] = Convert.ToInt16(Data);
                dgvData.Rows[row].Cells["实际值"].Value = int16buf[row];
            }
        }
        #endregion

        //读取数据
        #region    #endregion 
        private void ReadValue_Click(object sender, EventArgs e)
        {

            timer1.Enabled = true;
            for (int j = 0; j < aAddress.Length; j++)
            {
                Read[0] = 0x42;
                Read[1] = low[j];
                Read[2] = si[j];
                Read[3] = Subindex[j];
                form.DatatoSend(0x62C, Read);
                Thread.Sleep(50);
            }
        }
        #endregion

        //定时器
        #region 
        double Displayvalue;
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                for (int i = 0; i < aAddress.Length; i++)
                {
                    if (aDataDype[i] == 0)
                    {
                        dgvData.Rows[i].Cells["实际值"].Value = MainForm.uint16resdata[i];
                        Displayvalue = (MainForm.uint16resdata[i] * aGain[i] + aOffset[i]) / aBaseValue[i];
                        dgvData.Rows[i].Cells["显示值"].Value = RetainDecimal(Displayvalue, aDecimal[i]);
                        double Valuebata = Convert.ToDouble(RetainDecimal(Displayvalue, aDecimal[i]));
                        //if (MainForm.uint16resdata[i] > aMax[i])
                        //{
                        //    timer1.Stop();
                        //    dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                        //    MessageBox.Show("红色行的实际值大于最大值，读取已停止！");
                        //}
                        //if (MainForm.uint16resdata[i] < aMin[i])
                        //{
                        //    timer1.Stop();
                        //    dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                        //    MessageBox.Show("红色行的实际值小于最小值，读取已停止！");
                        //}
                    }
                    if (aDataDype[i] == 1)
                    {
                        dgvData.Rows[i].Cells["实际值"].Value = MainForm.int16resdata[i];
                        Displayvalue = (MainForm.int16resdata[i] * aGain[i] + aOffset[i]) / aBaseValue[i];
                        dgvData.Rows[i].Cells["显示值"].Value = RetainDecimal(Displayvalue, aDecimal[i]);
                        double Valuebata = Convert.ToDouble(RetainDecimal(Displayvalue, aDecimal[i]));
                        //if (MainForm.int16resdata[i] > aMax[i])
                        //{
                        //    timer1.Stop();
                        //    dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                        //    MessageBox.Show("红色行的实际值大于最大值，读取已停止！");
                        //}
                        //if (MainForm.int16resdata[i] < aMin[i])
                        //{
                        //    timer1.Stop();
                        //    dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                        //    MessageBox.Show("红色行的实际值小于最小值，读取已停止！");
                        //}
                        Thread.Sleep(10);
                    }
                    if (aDataDype[i] == 2)
                    {
                        dgvData.Rows[i].Cells["实际值"].Value = MainForm.uint16resdata[i];
                        Displayvalue = (MainForm.uint16resdata[i] * aGain[i] + aOffset[i]) / aBaseValue[i];
                        dgvData.Rows[i].Cells["显示值"].Value = StratBitNumber(MainForm.uint16resdata[i],aStratBit[i]);
                        double Valuebata = Convert.ToDouble(RetainDecimal(Displayvalue, aDecimal[i]));
                        //if (MainForm.uint16resdata[i] > aMax[i])
                        //{
                        //    timer1.Stop();
                        //    dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                        //    MessageBox.Show("红色行的实际值大于最大值，读取已停止！");
                        //}
                        //if (MainForm.uint16resdata[i] < aMin[i])
                        //{
                        //    timer1.Stop();
                        //    dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                        //    MessageBox.Show("红色行的实际值小于最小值，读取已停止！");
                        //}
                    }
                }
               
                timer1.Enabled = false;
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        #endregion 
        //二进制 从后往前数第strat bit的数  1=on 2=off 
        private static string StratBitNumber(UInt16 data,int StratBit)
        {
            string Data2 = Convert.ToString(data, 2);
            
            char[] ch = Data2.ToArray();
            Array.Reverse(ch,0,Data2.Length);
            string NewData2 = new StringBuilder().Append(ch).ToString();

            string strbit=NewData2[StratBit].ToString();
            if (strbit == "0")
            {
                return "ON";
            }
            else
            {
                return "OFF";
            }
           
        }
        //保留小数位
        #region 
        public static string RetainDecimal(double Data, int Precision)
        {

            switch (Precision)
            {
                case 1:
                    Data = Data / (float)Math.Pow(10, 1);

                    return $"{Data:F1}";

                case 2:
                    Data = Data / (float)Math.Pow(10, 2);
                    return $"{Data:F2}";

                case 3:
                    Data = Data / (float)Math.Pow(10, 3);
                    return $"{Data:F3}";

                case 4:
                    Data = Data / (float)Math.Pow(10, 4);
                    return $"{Data:F4}";

                case 5:
                    Data = Data / (float)Math.Pow(10, 5);
                    return $"{Data:F4}";

                default:
                    return $"{Data:F0}";
            }
        }
        #endregion

        //初始化视图，数组
        #region
        public void dgv_CellContentClick()
        {
            try
            {
                DataTable dt = new DataTable();
            //datagridview组件的颜色
            dgvData.RowsDefaultCellStyle.BackColor = Color.White;
            Console.WriteLine(cboSheet.SelectedItem.ToString());
            dt = DataSet.Tables[cboSheet.SelectedItem.ToString()];
            BindDataGridView(dt, dgvData);
            dgvData.DataSource = dt;
            for (int i = 0; i < this.dgvData.Columns.Count; i++)
            {
                this.dgvData.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            //dgvData.Rows.Clear();
            //获取参数
            for (int i = 0; i < aAddress.Length; i++)
            {
                aAddress[i] = dgvData.Rows[i].Cells[Address].Value;
                aDataDype[i] = Convert.ToInt32(dgvData.Rows[i].Cells[DataDype].Value);
                aGain[i] = Convert.ToInt32(dgvData.Rows[i].Cells[Gain].Value);
                aOffset[i] = Convert.ToInt32(dgvData.Rows[i].Cells[Offset].Value);
                aBaseValue[i] = Convert.ToDouble(dgvData.Rows[i].Cells[BaseValue].Value);
                aDecimal[i] = Convert.ToInt32(dgvData.Rows[i].Cells[Decimal].Value);
                aMax[i] = Convert.ToInt32(dgvData.Rows[i].Cells[Max].Value);
                aMin[i] = Convert.ToInt32(dgvData.Rows[i].Cells[Min].Value);
                aStratBit[i]= Convert.ToInt32(dgvData.Rows[i].Cells[StratBit].Value);
                }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (aAddress[i].ToString().Contains("+"))
                {
                    string str = aAddress[i].ToString().Substring(0, 1) + aAddress[i].ToString().Substring(2, 3) + "00";
                    aAddress[i] = str;
                    dgvData.Rows[i].Cells[2].Value = str;
                }
                //si[i] = (byte)Convert.ToInt32(aAddress[i].ToString().Substring(0, 2));
                //low[i] = (byte)Convert.ToInt32(aAddress[i].ToString().Substring(2, 2).PadLeft(2, '0'),16);
                //Subindex[i] = (byte)Convert.ToInt32(aAddress[i].ToString().Substring(4, 2).PadLeft(2, '0'));
                //if (RecBuffer[1] == 66  && RecBuffer[4] == 0 && RecBuffer[2] == Convert.ToByte("0x" + MainForm2.Slow[i], 16) && RecBuffer[3] == Convert.ToByte("0x" + MainForm2.Ssi[i], 16))                
                while (aAddress[i].ToString().Length != 6 || aAddress[i].ToString().IndexOf(" ") > 0)
                {
                    if (aAddress[i].ToString().IndexOf(" ") > 0)
                    {
                        
                        dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                        MessageBox.Show("Address列下的数值有包含空格的，红色行！，请检查并关闭窗口。", "错误信息");
                            break;
                    }
                    if (aAddress[i].ToString().Length != 6)
                    {
                        
                        dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Green;
                        MessageBox.Show("Address列下的数值有不等于六位的,绿色行！，请检查并关闭窗口。", "错误信息");
                            break;
                    }
                }
                if (aAddress[i].ToString().Length == 6 && aAddress[i].ToString().Substring(4, 2) != "00")
                {
                   
                    dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
                    MessageBox.Show("Address列下的数值有最后两位不为0的,黄色行！，请检查并关闭窗口。", "错误信息");
                }
                
                    Ssi[i] = aAddress[i].ToString().Substring(0, 2);
                    Slow[i] = aAddress[i].ToString().Substring(2, 2);
                    low[i] = Convert.ToByte("0x" + Slow[i], 16);
                    si[i] = Convert.ToByte("0x" + Ssi[i], 16);

                    a[i] = Convert.ToInt32("0x" + Ssi[i], 16);
                    Subindex[i] = 0;
                
                
               
            }
            // DataGridView取消选中第一行第一列方法(绑定数据源后)
            dgvData.Rows[0].Cells[0].Selected = false;
            dgvData.Rows[0].Selected = false;
        }          
        catch (Exception exp)
            {
                MessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
}

        public static void BindDataGridView(DataTable dt, DataGridView dgv)
        {
            try
            {
                dgv.DataSource = dt;
                dt.Columns.Add("实际值", typeof(int));
                dt.Columns.Add("显示值", typeof(string));

                dgv.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        //public static DataTable dataTable = new DataTable();
        #endregion

        //打开文件
        #region 
        public void thOpenFile()
        {
            try
            {
                DataTable dataTable = new DataTable();
                OpenFileDialog file = new OpenFileDialog();
                file.ShowDialog();
                file.Title = @"选择要打开的文件";
                file.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls|(*.csv)|*.csv";
                dataTable = ReadCsvToDataTable(file.FileName);
                txtFileName.Text = file.FileName;//对话框中选择的文件名
                dataTable.TableName = Path.GetFileNameWithoutExtension(file.FileName);
                //3：通过reader得到数据
                DataSet.Tables.Add(dataTable);
                cboSheet.Items.Clear();
                foreach (DataTable item in DataSet.Tables)
                {
                    cboSheet.Items.Add(item.TableName);
                    Console.WriteLine(item.TableName);
                }

            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        public static DataSet DataSet = new DataSet();
        public void OpenFile()
        {
            try
            {
                openfile = new ThreadStart(thOpenFile);//通过ThreadStart委托告诉子线程执行什么方法　　
                Thread th = new Thread(openfile);
                th.SetApartmentState(ApartmentState.STA);
                th.Start();//启动新线程
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }
        private void btnFilenpath_Click(object sender, EventArgs e)
        {
            OpenFile();
        }
        private void cboSheet_SelectedIndexChanged(object sender, EventArgs e)
        {
            dgv_CellContentClick();
        }
        #endregion

        //读取Csv文件
        #region 
        public static DataColumn dataColumn;
        public static DataTable dt = new DataTable();
        public static int len = 0;


        public static DataTable ReadCsvToDataTable(string path)
        {
            //try
            //{
                DataTable dt = new DataTable();
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("gb2312"));
                string strLine = "";//记录每次读取的一行记录

                string[] aryLine = null;//每行字段内容
                string[] tableHead = null;//
                int columnCount = 0;//列数
                bool IsFirst = true; //是否为第一行
                while ((strLine = sr.ReadLine()) != null)
                {
                    len++;
                    if (IsFirst == true)
                    {
                        tableHead = strLine.Split(',');
                        IsFirst = false;
                        columnCount = tableHead.Length;
                        //创建列
                        for (int i = 0; i < columnCount; i++)
                        {
                            dataColumn = new DataColumn(tableHead[i]);


                            dt.Columns.Add(dataColumn);
                        }

                    }
                    else
                    {
                        aryLine = strLine.Split(',');
                        DataRow dataRow = dt.NewRow();
                        for (int j = 0; j < columnCount; j++)
                        {
                            dataRow[j] = aryLine[j];
                        }
                        dt.Rows.Add(dataRow);
                    }
                }
                len = len - 1;
                aAddress = new object[len];
                aDataDype = new int[len];
                aGain = new int[len];
                aOffset = new int[len];
                aBaseValue = new double[len];
                aDecimal = new int[len];
                aMax = new int[len];
                aMin = new int[len];
                Slow = new string[len];
                Ssi = new string[len];
                low = new byte[len];
                si = new byte[len];
                Subindex = new byte[len];
                uint16buf = new UInt16[len];
                int16buf = new Int16[len];
                aStratBit = new int[len];
            if (aryLine != null && aryLine.Length > 0)
                {
                    dt.DefaultView.Sort = tableHead[0] + " " + "asc";
                }
                sr.Close();
                sr.Dispose();
                fs.Close();
                fs.Dispose();
            //}
            //catch (Exception exp)
            //{
            //    MessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            //}
            return dt;
           

           
        }

        //private void MainForm2_FormClosed(object sender, FormClosedEventArgs e)
        //{
        //    System.Environment.Exit(System.Environment.ExitCode);
        //    this.Dispose();
        //    this.Close();
        //}
    }
    
    #endregion 
}
